/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controladores;

import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import negocio.Usuario;

import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;


/**
 *
 * @author JAVA
 */
public class subirArchivo extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    private static final String TEMPORAL_DIR = "temp";
    private static final String DESTINO_DIR = "imagenes";
    private File tmp;
    private String nombre;
    private File des;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        
        // Compruebo si las carpetas existen y si no las creo
        // ************************************************************
        String ruta = getServletContext().getRealPath(TEMPORAL_DIR);
        tmp = new File(ruta);
        if (!tmp.exists()) {
            tmp.mkdir();
        }
        
        ruta = getServletContext().getRealPath(DESTINO_DIR);
        des = new File(ruta);
        if (!des.exists()) {
            des.mkdir();
        }
        
        
        DiskFileItemFactory dfif = new DiskFileItemFactory();
        dfif.setRepository(tmp);
        
        ServletFileUpload sfu = new ServletFileUpload(dfif);
        
        try {
            List datos = sfu.parseRequest(request);
            Iterator itr = datos.iterator();
            
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                
                if (!item.isFormField()) {
                    String[] arrStr = item.getName().split(new String ("\\\\"));
                    String nombreArchivo = arrStr[arrStr.length - 1];
                    String rutaFoto=getServletContext().getContextPath()+"/imagenes/";
                    HttpSession sesion=request.getSession();
                    Usuario u=(Usuario)sesion.getAttribute("usuario");
                    u.setFoto(rutaFoto+nombreArchivo);
                    u.actualizarUsuario();
                    
                    File archivo = new File(des, nombreArchivo);
                    
                    item.write(archivo);
                } else {
                    //Nombre del campo
                    if (item.getFieldName().equals("examinar")) {
                        nombre = item.getString();
                    }
                }
                
            }
            request.getRequestDispatcher("datosPersonales.jsp").forward(request, response);

        } catch (FileUploadException ex) {
            Logger.getLogger(subirArchivo.class.getName()).log(Level.SEVERE, null, ex);
        }catch (Exception ex) {
            Logger.getLogger(subirArchivo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
